local Grid = {}
local Cell = require('scripts.models.Cell')
function Grid:new(rows, cols, interval, structure)
	local grid = display.newGroup()
-- statics
	grid.rows = rows
	grid.cols = cols
	grid.gridWidth = X
	grid.gridHeight = Y
	grid.interval = interval
	grid.cellWidth = grid.gridWidth / cols
	grid.cellHeight = grid.gridHeight / rows
	grid.maxFireCells = 10
	grid.cells = {}
	grid.notNormalCells = {}
	grid.refreshTimeCount = 0
	
	local hasStructure = structure and rows == #structure and cols == #structure[0]
	for i = 1, rows do
		table.insert(grid.cells, {})
		for j = 1, cols do
			local cell, cellType = nil, 'normal'
			if hasStructure then
				-- short cut, including factory method in grid class
				cellType = sctructure[i][j]
			end
			cell = Grid:createCell(cellType, i, j, grid.cellWidth, grid.cellHeight)
			table.insert(grid.cells[i], cell)
			grid:insert(cell)
		end
	end

	function grid:update(delta) 
		self.refreshTimeCount = self.refreshTimeCount + delta
		if self.refreshTimeCount >= self.interval then
			self.refreshTimeCount = 0
			self:randomizeCells()
		end
	end

	function grid:randomizeCells() 
		local randomX, randomY;
		for i = #self.notNormalCells, 1, -1 do
			self.notNormalCells[i]:changeCellType('normal')

			table.remove(self.notNormalCells)
		end
		for i = 1, self.maxFireCells do
			randomX = math.random(1, self.rows)
			randomY = math.random(1, self.cols)
			self.cells[randomX][randomY]:changeCellType('fire')
			table.insert(self.notNormalCells, self.cells[randomX][randomY])
		end
	end

	function grid:getCells()
		return grid.cells
	end

	function grid:getCellFromCoordinates(x, y)
		local col = math.floor(x / self.cellWidth) + 1
		local row = math.floor(y / self.cellHeight) + 1
		-- print (row, col, self.cells[row][col].cellType, x, y)
		return self.cells[row][col]
	end
	return grid
end
--factory method for creating cells
function Grid:createCell(cellType, i, j, w, h)
	local cell = nil
	local centerX = w / 2 + w * (j - 1)
	local centerY = h / 2 + h * (i - 1)
	local sprite = 'normal'
	if cellType == 'fire' then
		sprite = 'fire'
	end
	cell = Cell:new(centerX, centerY, w - 2, h - 2, sprite)
	return cell
end

return Grid